package zlx.springboot.jsp.Service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import zlx.springboot.jsp.Service.CustomerService;
import zlx.springboot.jsp.domain.Customer;
import zlx.springboot.jsp.domain.CustomerExample;
import zlx.springboot.jsp.mapper.CustomerMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {
    final private Logger logger= LoggerFactory.getLogger(CustomerServiceImpl.class);
    @Resource
    private CustomerMapper customerMapper;
    @Override

    /**
     * @Author Edward
     * @Description 测试使用注解缓存机制缓存
     * 参数详解
     * （1）cacheNames：缓存的名称，必须指定一个，至少一个
     * （2）key：缓存的key，可以使用SpEL表达式来写
     * （3）condition：判断缓存的条件，必须是true才缓存，可以使用SpEL表达式来编写
     * @Date 13:15 2020/6/26
     * @Param [name]
     * @return customers
     **/
    //开启缓存
    @Cacheable(cacheNames = {"customer"},key = "#name",condition = "#a0!=null")
    public List<Customer> queryAllCustomerInfo(String name) {
        System.out.println("查询数据");
        CustomerExample example=new CustomerExample();
        if(name!=null&&!"".equals(name)){
            logger.info("正在搜素用户，请稍后...");
            example.createCriteria().andCustNameLike("%"+name+"%");
        }
        List<Customer> customers = customerMapper.selectByExample(example);
        return customers;
    }

    @Override
    @CachePut(cacheNames = {"customer"},key = "#customer.custName")
    //使用@cacheput更新缓存
    public List<Customer>  updateCustomerInfoByID(Customer customer){
        List<Customer> customers = new ArrayList<Customer>();
        CustomerExample example =new CustomerExample();
        example.createCriteria().andCustIdEqualTo(customer.getCustId());
        customerMapper.updateByExample(customer, example);
        customers.add(customer);
        return customers;
    }
    /**
     * @Author Edward
     * @Description 根据用户id查用户信息
     * @Date 13:28 2020/6/27
     * @Param [id]
     * @return zlx.springboot.jsp.domain.Customer
     **/
    @Override
    @Cacheable(cacheNames = "customer",key = "#id")
    @CacheEvict()
    public Customer queryCustomerById(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }
    //根据客户id删除客户
    @Override
    public void deleteCustomerInfoByID(Long id) {
        customerMapper.deleteByPrimaryKey(id);
    }
}
